//
//  UICollectionViewEx.swift
//
//  Created by Python on 2024/6/16.
//

import UIKit

extension UICollectionView {
    func register<Cell: UICollectionViewCell>(cellClass: Cell.Type) {
        register(cellClass, forCellWithReuseIdentifier: Self.stringFromClass(cellClass))
    }

    func dequeueReusableCell<Cell: UICollectionViewCell>(cellClass: Cell.Type, for indexPath: IndexPath) -> Cell {
        let cell = dequeueReusableCell(withReuseIdentifier: Self.stringFromClass(cellClass), for: indexPath) as! Cell
        return cell
    }

    /// 计算竖直滑动,cell宽度自适应,高度恒定的UICollectionview的所有cell加起来的高度
    /// - Parameters:
    ///   - collectionWidth: collectionView的宽度
    ///   - interSpace: cell之间的水平间距
    ///   - lineSpace: cell之间的竖直间距
    ///   - itemWidths: 所有cell的宽度
    ///   - itemHeight: cell的高度
    ///   - numberOfLines: 最多显示多少行
    ///   - sectionInset: ...
    static func calculateContentHeight(collectionWidth: CGFloat,
                                       interSpace: CGFloat,
                                       lineSpace: CGFloat,
                                       itemWidths: [CGFloat],
                                       itemHeight: CGFloat,
                                       numberOfLines: Int = 0,
                                       sectionInset: UIEdgeInsets = .zero) -> CGFloat {
        let collectionWidth = collectionWidth - sectionInset.left - sectionInset.right
        // 如果数据源为空,返回0.0
        if itemWidths.isEmpty { return 0.0 }
        // cell行数
        var rows = 0
        // 当前行的cell个数
        var row_count = 0
        // 当前行的内容(cell+间距)总宽度
        var row_width: CGFloat = 0.0
        // 换行操作
        func nextRow(with itemWidth: CGFloat) {
            rows += 1
            row_count = 1
            row_width = itemWidth
        }
        // 遍历cell的size
        for (index, itemWidth) in itemWidths.enumerated() {
            if index == 0 {
                nextRow(with: itemWidth)
            } else {
                // 计算当前行宽度
                row_width += (interSpace + itemWidth)
                if row_width > collectionWidth { // 如果当前行宽度大于collectionView宽度
                    if row_count <= 0 { // 如果当前行cell个数为0,不换行
                        // 当前行cell个数+1
                        row_count += 1
                    } else { // 换行
                        nextRow(with: itemWidth)
                    }
                } else { // 如果当前宽度小于collectionView宽度,不用换行
                    // 当前行cell个数+1
                    row_count += 1
                }
            }
        }

        // 计算总高度
        var _rows = rows
        if numberOfLines > 0 {
            _rows = min(rows, numberOfLines)
        }
        let contentH = CGFloat(_rows) * itemHeight + CGFloat(_rows - 1) * lineSpace
        return contentH
    }
    
    /// class转string
    static func stringFromClass(_ aClass: AnyClass) -> String {
        return String(describing: aClass)
    }
}
